package models

import (
	"errors"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type ParamsMangerModel struct {
	BaseModel   `xorm:"extends"`
	Name        string `json:"name"`
	Required    string `xorm:"required"  json:"required"`
	NotRequired string `xorm:"not_required"  json:"not_required"`
}

func (sm *ParamsMangerModel) TableName() string {
	return "params_manger"
}

func (sm *ParamsMangerModel) Insert() error {
	_, err := app.DB().Insert(sm)
	if err != nil {
		return err
	}
	return nil
}

func (sm *ParamsMangerModel) SelectByType(name string) (*ParamsMangerModel, error) {
	doc := &ParamsMangerModel{}
	s := app.DB().Table("params_manger")

	if name != "" {
		s = s.Where("name = ?", name)
	}
	has, err := s.Get(doc)
	if err != nil {
		middlewares.Logger.Println("find by ParamsMangerModel", err)
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return doc, err
}

func (sm *ParamsMangerModel) SelectByNameAll(name string) ([]ParamsMangerModel, error) {
	doc := make([]ParamsMangerModel, 0)
	if name == "" {
		return nil, nil
	}
	s := app.DB().Table("treatment_line").OrderBy("name asc").Where("name like ?", "%"+name+"%")

	_, err := s.FindAndCount(&doc)
	if err != nil {
		return nil, err
	}
	return doc, err
}

func (sm *ParamsMangerModel) SelectById(id string) (*ParamsMangerModel, error) {
	doc := &ParamsMangerModel{}
	has, err := app.DB().Where("id = ?", id).Get(doc)
	if err != nil {
		middlewares.Logger.Println("find by ParamsMangerModel", err)
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return doc, err
}

func (sm *ParamsMangerModel) UpdateData(req *ParamsMangerModel, id string) error {
	_, err := app.DB().ID(id).Update(req)
	if err != nil {
		middlewares.Logger.Println("ParamsMangerModel Update failed ", err)
		return errors.New("数据修改失败")
	}
	return nil
}

func (sm *ParamsMangerModel) SelectAll() ([]ParamsMangerModel, error) {
	doc := make([]ParamsMangerModel, 0)
	s := app.DB().Table("treatment_line").OrderBy("name asc").Where("deleted_at is null")

	_, err := s.FindAndCount(&doc)
	if err != nil {
		return nil, err
	}
	return doc, err
}

func (sm *ParamsMangerModel) DeleteTreatmentLine(id string) error {
	doc := &ParamsMangerModel{}
	_, err := app.DB().Where("id = ?", id).Delete(doc)
	if err != nil {
		middlewares.Logger.Println("delete by DeleteTreatmentLine", err)
		return err
	}
	return err
}
